<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form pt-[15px] border-bottom">
      <el-form>
        <el-row :gutter="12">
          <el-col :span="5">
            <el-form-item>
              <div class="w-full flex justify-between">
                <el-date-picker
                  v-model="form.Date"
                  type="daterange"
                  unlink-panels
                  range-separator="－"
                  start-placeholder="选择开始时间"
                  end-placeholder="选择结束时间"
                  :disabled-date="disableFutureDates"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.ActivityType">
                <el-option label="全部活动" value="-1" />
                <el-option label="优惠活动" value="0" />
                <el-option label="大转盘" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.Level">
                <el-option label="全部场次" value="-1" />
                <el-option label="初级场" value="0" />
                <el-option label="中级场" value="1" />
                <el-option label="高级场" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.Status">
                <el-option label="全部状态" value="-1" />
                <el-option label="待审核" value="0" />
                <el-option label="已通过" value="1" />
                <el-option label="已拒绝" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-input v-model="form.Name" placeholder="请输入会员账号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="flex">
              <div class="mr-[10px]">
                <el-checkbox
                  label="仅查看中奖"
                  v-model="form.IsWinning"
                  :true-value="1"
                  :false-value="0"
                />
              </div>
              <el-form-item>
                <el-button type="primary" @click.stop="search">搜索</el-button>
                <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pt-[10px] flex justify-between items-center">
      <div>
        <el-button type="success" @click="handleBtnDate('today')">今天</el-button>
        <el-button type="success" @click="handleBtnDate('yesterday')">昨天</el-button>
        <el-button type="success" @click="handleBtnDate('thisWeek')">本周</el-button>
        <el-button type="success" @click="handleBtnDate('lastWeek')">上周</el-button>
        <el-button type="success" @click="handleBtnDate('thisMonth')">本月</el-button>
        <el-button type="success" @click="handleBtnDate('lastMonth')">上月</el-button>
      </div>
      <div>
        <el-button
          v-if="premsStore.isEditActivitySetting"
          type="success"
          @click="handleBatchVerify(1)"
        >
          批量通过
        </el-button>
        <el-button
          v-if="premsStore.isEditActivitySetting"
          type="success"
          @click="handleBatchVerify(2)"
        >
          批量拒绝
        </el-button>
      </div>
    </div>
    <div class="grow-[1] h-0 mt-[10px]">
      <el-table
        scrollbar-always-on
        ref="elTableRef"
        v-loading="state.loading"
        :data="list"
        style="width: 100%"
        height="100%"
        border
        stripe
        fit
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column align="center" type="selection" width="40" />
        <el-table-column align="center" label="序号" width="60">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="ActivityType"
          align="center"
          label="活动类型"
          width="80"
          show-overflow-tooltip
        >
          <template #default="{ row }: TableItem">
            {{ row.ActivityType == 0 ? "优惠活动" : "大转盘" }}
          </template>
        </el-table-column>
        <el-table-column prop="Level" align="center" label="等级" width="80">
          <template #default="{ row }: TableItem">
            {{ levelMap[row.Level] }}
          </template>
        </el-table-column>
        <el-table-column prop="Username" align="center" label="会员" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Username || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="Nickname" align="center" label="昵称" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Nickname || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="Note" align="center" label="备注" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Note || "--" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="CreatedAt"
          label="抽奖时间"
          width="100"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }: TableItem">
            {{ row.CreatedAt ? formatDate(row.CreatedAt, "YYYY-MM-DD") : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="UpdatedAt"
          label="审核时间"
          width="100"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }: TableItem">
            {{ row.UpdatedAt ? formatDate(row.UpdatedAt, "YYYY-MM-DD") : "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="RewardType" width="80" align="center" label="奖品类型">
          <template #default="{ row }: TableItem">
            {{ row.RewardType == 1 ? "奖金" : "奖品" }}
          </template>
        </el-table-column>
        <el-table-column prop="RewardAmount" align="center" label="奖品">
          <template #default="{ row }: TableItem">
            {{ row.RewardAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="Status" width="80" align="center" label="审核状态">
          <template #default="{ row }: TableItem">
            <span
              :class="{
                'text-blue': row.Status == 0,
                'text-green': row.Status == 1,
                'text-red': row.Status == 2
              }"
            >
              {{ statusMap[row.Status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="GiveMethod" width="100" align="center" label="发放方式">
          <template #default="{ row }: TableItem">
            {{ row.GiveMethod == 1 ? "人工审核" : "自动发放" }}
          </template>
        </el-table-column>
        <el-table-column prop="Issuer" align="center" label="操作人" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Issuer || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center">
          <template #default="{ row }: TableItem">
            <div v-if="row.Status != 0">--</div>
            <el-button
              type="success"
              size="small"
              v-if="row.Status == 0 && premsStore.isEditActivitySetting"
              @click="handleVerify(row.Id, 1, '通过')"
              >通过</el-button
            >
            <el-button
              type="danger"
              size="small"
              v-if="row.Status == 0 && premsStore.isEditActivitySetting"
              @click="handleVerify(row.Id, 2, '拒绝')"
              >拒绝</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
  </div>
</template>
<script setup lang="ts">
import moment from "moment";
import { useList } from "@/hooks/useList";
import { getDateArray, disableFutureDates, formatDate } from "@/utils/common";
import { ElMessageBox, ElTable } from "element-plus";
import { message } from "@/utils/message";
import { reqActivityDiscountRecord, reqActivityDiscountRecordAudit } from "@/api/activity";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: DiscountRecordMo;
}

const selectDate = ref<string>("today");
const getDate = () => {
  const date: Record<string, string[]> = getDateArray();
  return date;
};
const form = reactive({
  Name: "",
  ActivityType: "-1",
  Level: "-1",
  Status: "-1",
  IsWinning: 0,
  Date: <string[] | "">getDateArray()["today"]
});
const premsStore = usePremsStore();
const multipleSelection = ref<number[]>([]);
const levelMap: Record<string, string> = {
  0: "初级场",
  1: "中级场",
  2: "高级场"
};
const statusMap: Record<string, string> = {
  0: "待审核",
  1: "已发放",
  2: "已拒绝"
};
const getParams = () => {
  const params: any = {
    IsWinning: form.IsWinning
  };
  if (form.Name) {
    params.Name = form.Name;
  }
  if (form.Status && form.Status != "-1") {
    params.Status = form.Status;
  }
  if (form.ActivityType && form.ActivityType != "-1") {
    params.ActivityType = form.ActivityType;
  }
  if (form.Level && form.Level != "-1") {
    params.Level = form.Level;
  }
  if (form.Date) {
    params.StartDate = moment(form.Date[0]).format("YYYY-MM-DD 00:00:00");
    params.EndDate = moment(form.Date[1]).format("YYYY-MM-DD 23:59:59");
  }
  return params;
};

const { elTableRef, state, list, getData, search } = useList<DiscountRecordMo, any>(
  reqActivityDiscountRecord,
  getParams
);

// 重置
const handleRefresh = () => {
  selectDate.value = "";
  form.Name = "";
  form.Status = "-1";
  form.ActivityType = "-1";
  form.Level = "-1";
  form.IsWinning = 0;
  form.Date = getDateArray()["today"];
  selectDate.value = "today";
  search();
};

const handleBtnDate = (str: string) => {
  const date = getDate();
  selectDate.value = str;
  form.Date = date[str];
  search();
};

const handleSelectionChange = (val: DiscountRecordMo[]) => {
  multipleSelection.value = val.map(item => item.Id);
};

// 通过拒绝
const handleVerify = (id: number, status: number, text: string) => {
  ElMessageBox.confirm(`是否进行【${text}】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqActivityDiscountRecordAudit({
            Ids: [id],
            Status: status
          });
          getData();
          message.success(`${text}成功`);
          instance.confirmButtonLoading = false;
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

// 批量通过拒绝
const handleBatchVerify = (status: number) => {
  if (multipleSelection.value.length == 0) {
    message.warning("请选择要审核的会员");
    return;
  }
  ElMessageBox.confirm(`是否进行【${status == 1 ? "批量通过" : "批量拒绝"}】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqActivityDiscountRecordAudit({
            Ids: multipleSelection.value,
            Status: status
          });
          getData();
          multipleSelection.value = [];
          message.success(`${status == 1 ? "批量通过" : "批量拒绝"}成功`);
          instance.confirmButtonLoading = false;
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
:deep() {
  .el-table__cell .cell {
    padding: 0 4px !important;
  }
}
</style>
